import request from "@/utils/request";
import { defineComponent, createApp, h } from 'vue'
import PreviewDocumentVue from "@/components/requirement/previewDocument.vue";
// TODO
// 初始搜索时间范围
export const getSearchTimes = (val: any) => {
  // 创建一个新的日期对象
  const date = new Date(val);

  // 获取日期的各个部分
  const Y = date.getFullYear();
  const M = date.getMonth() + 1;
  const D = date.getDate();

  const createAtBegin = new Date(
    new Date(Y, M - 1, 1).setHours(0, 0, 0)
  ).toISOString(); //默认开始时间
  const createAtEnd = new Date(
    new Date(Y, M - 1, D).setHours(23, 59, 59)
  ).toISOString(); //默认结束时间
  return [createAtBegin, createAtEnd];
};

// 快捷时间筛选
export const getShortCuts = () => {
  const shortcuts = [
    {
      text: "最近一周",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        new Date(start.setHours(0, 0, 0)).toISOString();
        new Date(end.setHours(23, 59, 59)).toISOString();
        return [start, end];
      },
    },
    {
      text: "最近一个月",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
        new Date(start.setHours(0, 0, 0)).toISOString();
        new Date(end.setHours(23, 59, 59)).toISOString();
        return [start, end];
      },
    },
    {
      text: "最近三个月",
      value: () => {
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
        new Date(start.setHours(0, 0, 0)).toISOString();
        new Date(end.setHours(23, 59, 59)).toISOString();
        return [start, end];
      },
    },
  ];
  return shortcuts;
};

export const formatDateTime = (isoString: string): string => {
  const date = new Date(isoString);
  const formatter = new Intl.DateTimeFormat('en-GB', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false,
  });
  return formatter.format(date).replace(/\//g, '-').replace(',', '');
};

// 时间格式化方法
export const formatDate = (cellValue: string) => {
  // cellValue 可能是 ISO 格式的时间字符串
  if (cellValue) {
    const date = new Date(cellValue);
    if (
      "1/1/1 08:05:43" ==
      date.toLocaleDateString("zh-CN") + " " + date.toLocaleTimeString("zh-CN")
    ) {
      return null;
    }
    return date.toLocaleDateString("zh-CN");
  }
  return null;
};

// 日期格式化方法
export const tableTimeDate = (val: string) => {
  if (val == "0001-01-01T00:00:00Z" || val == null) {
    return null;
  } else {
    // 支持包含 "T" 的 ISO 字符串与包含空格的日期时间字符串
    const pure = val.includes("T") ? val.split("T")[0] : val.split(" ")[0];
    return pure;
    /*  // 创建一个新的日期对象
     const date = new Date(val);
 
     // 获取日期的各个部分
     const Y = date.getFullYear().toString().padStart(4, "0");
     const M = (date.getMonth() + 1).toString().padStart(2, "0");
     const D = date.getDate().toString().padStart(2, "0");
 
     // 获取时间的各个部分
     /*  const h = (date.getHours()).toString().padStart(2,"0");
     const m = (date.getMinutes()).toString().padStart(2,"0");
     const s = (date.getSeconds()).toString().padStart(2,"0"); */

    // // const timeDate = `${Y}/${M}/${D}/ ${h}:${m}:${s}`;
    // const timeDate = `${Y}/${M}/${D}`;
    // return timeDate;
  }
};
// 时间格式化方法: YYYY/MM/DD HH:MM:SS
export const tableTimeDateMsg = (val: string) => {
  // 创建一个新的日期对象
  const date = new Date(val);

  // 获取日期的各个部分
  const Y = date.getFullYear().toString().padStart(4, "0");
  const M = (date.getMonth() + 1).toString().padStart(2, "0");
  const D = date.getDate().toString().padStart(2, "0");

  // 获取时间的各个部分
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");

  const time = `${Y}/${M}/${D} ${h}:${m}:${s}`;
  return time;
};

// 时间格式化方法: YYYY-MM-DD HH:MM:SS
export const tableTimeDateMsg2 = (val: string) => {
  if (val == "0001-01-01T00:00:00Z" || val == null) {
    return null;
  } else {
    // 创建一个新的日期对象
    const date = new Date(val);

    // 获取日期的各个部分
    const Y = date.getFullYear().toString().padStart(4, "0");
    const M = (date.getMonth() + 1).toString().padStart(2, "0");
    const D = date.getDate().toString().padStart(2, "0");

    // 获取时间的各个部分
    const h = date.getHours().toString().padStart(2, "0");
    const m = date.getMinutes().toString().padStart(2, "0");
    const s = date.getSeconds().toString().padStart(2, "0");

    const time = `${Y}-${M}-${D} ${h}:${m}:${s}`;
    return time;
  }
};

// 时间格式化方法
export const tableTimeDateMsgTow = (val: string) => {
  if (val == "0001-01-01T00:00:00Z" || val == null) {
    return null;
  } else {
    // 创建一个新的日期对象
    const date = new Date(val);

    // 获取日期的各个部分
    const Y = date.getFullYear().toString().padStart(4, "0");
    const M = (date.getMonth() + 1).toString().padStart(2, "0");
    const D = date.getDate().toString().padStart(2, "0");

    // 获取时间的各个部分
    const h = date.getHours().toString().padStart(2, "0");
    const m = date.getMinutes().toString().padStart(2, "0");
    const s = date.getSeconds().toString().padStart(2, "0");

    const time = `${Y}-${M}-${D}T${h}:${m}:${s}+08:00`;
    return time;
  }
};


// 获取字符串time的日期部分
export const timeToData = (val: string | null) => {
  if (!val) return null;
  const date = val.split(" ")[0];
  return date;
};


//  规定预计上线时间为today及之后，之前的不可选
export const disabledDate = (time: any) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return time.getTime() < today.getTime();
};

/**
 * 判断 time1 是否超过 time2
 * @param {Date} time1 第一个时间对象
 * @param {Date} time2 第二个时间对象
 * @returns {Object | null}
 */
export const checkTimeout = (time1: any, time2: any) => {
  // 如果 time1 为 null，则使用当前时间作为比较基准
  const currentTime = new Date();
  const compareTime = time1 == null ? currentTime : time1;

  // 获取两个时间的时间戳
  const compareTimeTimestamp = compareTime.getTime();
  const time2Timestamp = time2.getTime();

  // 判断 time1 是否超过 time2
  if (compareTimeTimestamp > time2Timestamp) {
    return { result: true, text: '超时原因' };
  }
  return { result: false, text: '未超时' };
};


// TODO
// 点击图片全屏显示
export const fullScreenImg = (event: MouseEvent) => {
  // 检查点击的是否是图片
  if ((event.target as HTMLElement)?.tagName === 'IMG') {
    const targetImage = event.target as HTMLImageElement;
    // 判断是否处于全屏状态
    if (!document.fullscreenElement) {
      // 请求全屏
      targetImage.requestFullscreen().catch((err) => {
        // 处理无法进入全屏的情况
        console.error("Error attempting to enable full-screen mode:", err);
      });
    } else {
      // 退出全屏
      document.exitFullscreen().catch((err) => {
        // 处理无法退出全屏的情况
        console.error("Error attempting to disable full-screen mode:", err);
      });
    }
  }
};

// 去除HTML数据中的空行
export const removeEmptyLines = (val: string) => {
  const regex = /<p[^>]*><\/p>|<br\s*\/?>/g;
  return val.replace(regex, "");
};

// "Enter"事件的方法
export const addEnterEvent = (inputId: any, callback: any) => {
  var input = document.getElementById(inputId);
  if (input) {
    input.addEventListener('keypress', function (event) {
      if (event.key === 'Enter' || event.keyCode === 13) {
        callback();
      }
    })
  } else {
    console.log('Global Enter key was pressed');
  }
};

// 验证输入框中的字符串是否为空
export const isValidateString = (data: string) => {
  console.log("字符串内容：", data);
  if (data.trim() === '') {
    // 校验不通过
    return true;
  } else {
    // 校验通过
    return false;
  }
};

// 验证输入框是否为空或空行
export const validateInput = (rule: any, value: any, callback: any) => {
  if (value === '' || value.trim() === '') {
    callback(new Error("必填，且不能为空或空格。"));
  } else {
    callback();
  }
};

// 验证数字不能为0的整数，且不能为空
export const validateNumber = (rule: any, value: any, callback: any) => {
  if (value == null || value == 0) {
    callback(new Error("必填，且不能为0"));
  } else {
    callback();
  }
};

// 验证富文本编辑器内容是否为空格或空行
export const isValidateEditor = (msg: any) => {
  const isImgTag = /<img[^>]*>/i.test(msg);
  if (isImgTag) {
    return false;
  } else {
    // 移除所有 HTML 标签
    const noTagsMsg = msg.replace(/<[^>]*>/g, '');

    // 检查是否只包含空行或空格
    const lines = noTagsMsg.split('&nbsp;');
    return lines.every((line: any) => line.trim() === '' || line.trim() === ' ');
  }
};

// 【我负责的任务】中当前用户区分测试true和研发false
export const isUserAuthId = (val: any) => {
  if (val == '111' || val == '666') {
    return true;
  } else if (val == '555' || val == '777' || val == '999') {
    return false;
  }
};

// 获取需求中的标题部分
export const projectTitle = (val: any) => {
  const parts = val.split('】');
  const result = parts[2] || ''; // 取第三个部分（索引2） 
  return result;
};

// 创建任务类型
export const taskTypeContent = (val: number) => {
  switch (val) {
    case 1:
      return {
        status: 1,
        text: "上线",
        color: "#ff0000"
      };
    case 2:
      return {
        status: 2,
        text: "运维",
        color: "#ff9900"
      };
    case 3:
      return {
        status: 3,
        text: "回归",
        color: "#19be6b"
      };
    case 4:
      return {
        status: 4,
        text: "日常",
        color: "#2d8cf0"
      };
    default:
      return {
        status: 1,
        text: "上线",
        color: "#ff0000"
      };
  }
};
// 分配任务类型
export const isTsContent = (val: number) => {
  switch (val) {
    case 1:
      return {
        status: 1,
        text: "研发任务",
        color: "#2d8cf0",
        content: "研发"
      };
    case 2:
      return {
        status: 2,
        text: "运维任务",
        color: "#ff9900",
        content: "运维"
      };
    case 3:
      return {
        status: 3,
        text: "测试任务",
        color: "#19be6b",
        content: "测试"
      };
    default:
      return {
        status: 1,
        text: "研发任务",
        color: "#2d8cf0",
        content: "研发"
      };
  }
};

// 各需求/任务状态数据
export const fatherStatus = (val: number) => {
  switch (val) {
    case 1:
      return {
        status: 1,
        text: "待分配",
        bgColor: "#ff9900",
        operate: "分配",
      };
    case 2:
      return {
        status: 2,
        text: "待开发",
        bgColor: "#2d8cf0",
        operate: "开发"
      };
    case 3:
      return {
        status: 3,
        text: "开发中",
        bgColor: "#ff9900",
        operate: "提测"
      };
    case 4:
      return {
        status: 4,
        text: "详细设计确认中",
        bgColor: "#13c2c2",
        operate: "审核"
      };
    case 5:
      return {
        status: 5,
        text: "测试中",
        bgColor: "#52c41a",
        operate: "是否通过"
      };
    case 6:
      return {
        status: 6,
        text: "待上线评审",
        bgColor: "#189cff",
        operate: "分配"
      };
    case 7:
      return {
        status: 7,
        text: "待上线",
        bgColor: "#6554ec",
        operate: ""
      };
    case 8:
      return {
        status: 8,
        text: "已上线",
        bgColor: "#04a204",
        operate: "评分"
      };
    case 9:
      return {
        status: 9,
        text: "已关闭",
        bgColor: "#909399",
        operate: "撤回"
      };
    default:
      return {
        status: 9,
        text: "已关闭",
        bgColor: "#909399",
      };
  }
};


// 各需求审核状态数据
export const enterStatus = (val: number) => {
  switch (val) {
    case 1:
      return {
        status: 1,
        text: "待审核",
        bgColor: "#F56C6C",
        content: "待审核",
        operate1: "催他"
      };
    case 2:
      return {
        status: 2,
        text: "未通过",
        bgColor: "#E6A23C",
        content: "未通过",
        operate1: "审核记录"
      };
    case 3:
      return {
        status: 3,
        text: "已通过",
        bgColor: "#67C23A",
        content: "已通过",
        operate1: "选择技术负责人"
      };
    default:
      return {
        status: 1,
        text: "待审核",
        bgColor: "#DF0101",
        content: "待审核",
        operate1: "催他"
      };
  }
};

// 是否需要测试参与
export const isGetTestStatus = (val: number) => {
  switch (val) {
    case 1:
      return {
        status: 1,
        text: "测试未参与",
        color: "#DF0101"
      };
    case 2:
      return {
        status: 2,
        text: "测试参与",
        color: "#67C23A"
      };
    case 3:
      return {
        status: 2,
        text: "待定",
        color: "#E6A23C"
      };
  }
}

// 测试状态
export const testStatus = (val: number) => {
  switch (val) {
    case 1:
      return {
        status: 1,
        text: "未生效",
        bgColor: "#ed4014",
      };
    case 2:
      return {
        status: 2,
        text: "待测试",
        bgColor: "#ff9900",
      };
    case 3:
      return {
        status: 3,
        text: "测试中",
        bgColor: "#52c41a",
      };
    case 4:
      return {
        status: 4,
        text: "测试通过",
        bgColor: "#52c41a",
      };
    case 5:
      return {
        status: 5,
        text: "测试未通过",
        bgColor: "#ed4014",
      };
    default:
      return {
        status: val,
        text: "未生效",
        bgColor: "#ed4014",
      }
  }
};

// 上线结果
export const requirementOnlineStatus = (val: number) => {
  switch (val) {
    case 1:
      return {
        status: 1,
        text: "未上线",
        color: "#909399",
        content: "待上线"
      };
    case 2:
      return {
        status: 2,
        text: "成功",
        color: "#67C23A",
        content: "上线成功"
      };
    case 3:
      return {
        status: 3,
        text: "失败",
        color: "#DF0101",
        content: "待上上线失败线"
      };
    default:
      return {
        status: 1,
        text: "未上线",
        color: "#909399",
        content: "待上线"
      };

  }
}

// 上线参与类型
export const bearStatus = (val: number) => {
  switch (val) {
    case 1:
      return {
        status: 1,
        text: "研发",
      };
    case 2:
      return {
        status: 2,
        text: "运维",
      };
    case 3:
      return {
        status: 3,
        text: "测试",
      };
  }
};
// 文件类型定义
export const fileType = (val: number, id: any, files: string) => {
  switch (val) {
    case 1:
      return {
        type: 1,
        text: "draftPath",
        content: "需求草稿",
        formData: {
          itemRequirementId: id,
          fileType: val,
          draftPath: files,
          summaryPath: null,
          detailedPath: null,
          meetingPath: null,
          onLineMeetingPath: null,
        }
      };
    case 2:
      return {
        type: 2,
        text: "summaryPath",
        content: "概要设计",
        formData: {
          itemRequirementId: id,
          fileType: val,
          draftPath: null,
          summaryPath: files,
          detailedPath: null,
          meetingPath: null,
          onLineMeetingPath: null,
        }
      };
    case 3:
      return {
        type: 3,
        text: "detailedPath",
        content: "详细设计",
        formData: {
          itemRequirementId: id,
          fileType: val,
          draftPath: null,
          summaryPath: null,
          detailedPath: files,
          meetingPath: null,
          onLineMeetingPath: null,
        }
      };
    case 4:
      return {
        type: 4,
        text: "meetingPath",
        content: "需求评审会议纪要",
        formData: {
          itemRequirementId: id,
          fileType: val,
          draftPath: null,
          summaryPath: null,
          detailedPath: null,
          meetingPath: files,
          onLineMeetingPath: null,
        }
      };
    case 5:
      return {
        type: 5,
        text: "onLineMeetingPath",
        content: "上线评审会议纪要",
        formData: {
          itemRequirementId: id,
          fileType: val,
          draftPath: null,
          summaryPath: null,
          detailedPath: null,
          meetingPath: null,
          onLineMeetingPath: files,
        }
      };
    default: {
      return {
        type: 0,
        text: "other",
        content: "其它"
      }
    }
  }
};

// 处理多文件字符串
export const handleFileNameList = (val: string | null | undefined) => {
  // 检查 val 是否为 null、undefined 或空字符串
  if (!val) {
    return []; // 返回空数组或其他默认值
  }

  if (val.includes("|")) {
    const files = val.split("|").filter(url => url.trim() !== "");
    return files;
  } else {
    return [val];
  }
};

// 处理参与人员中的字符串中的“|”
export const handleStringNames = (val: string) => {
  if (val !== '' && val.includes("|")) {
    const str = val.replace(/\|(?=[^|]*:)/g, "；").replace(/\|/g, "、");
    return str;
  } else {
    return val;
  }
};


// 辅助函数：格式化时间戳
function formatTimestamp(timestamp: string | undefined): string {
  if (!timestamp) {
    return "";
  }
  return timestamp
    .replace("年", "-")
    .replace("月", "-")
    .replace("日", " ")
    .replace("分", ":")
    .replace("时", ":")
    .replace("秒", "");
}

// 处理文件地址
export const handleFileName = (val: string) => {
  const fileName = val.split("/").pop() || "";
  const parts = fileName.split("_");

  const name = parts[1]; // 用户名称
  const timestamp = parts[2]; // 时间戳
  const fileNameDescription = parts.slice(3).join("_"); // 文件描述

  const type = fileName.split(".").pop() || 'txt';

  return {
    url: val, // 完整的文件路径
    type: type, // 文件类型
    name: name, // 用户名称
    timestamp: formatTimestamp(timestamp), // 时间戳
    fileName: fileNameDescription // 文件描述
  };
};

// 处理多文件地址
export const handleFilesNames = (files: string) => {
  const filesList = handleFileNameList(files).map((item: any) => handleFileName(item));
  return filesList;

};

// 下载文件方法
export const handleDownloadFile = async (val: any, baseUrl: string) => {
  const isImage = val.url.includes('Img');
  if (isImage) {
    window.open(`${import.meta.env.VITE_SERVE + val.url}`, '_blank');
    return;
  } else {
    try {
      // const fullUrl = `${baseUrl}${val.url}`;
      const fullUrl = val.url;


      // 检查响应状态码
      const response = await fetch(fullUrl, { method: 'HEAD' });
      if (!response.ok) {
        throw new Error(`服务器返回错误状态码：${response.status}`);
      };

      let downloadUrl = fullUrl;
      let needRevoke = false;

      // 如果是图片类型，使用Blob方式下载
      if (isImage) {
        const response = await fetch(fullUrl);
        if (!response.ok) throw new Error('下载失败');
        const blob = await response.blob();
        downloadUrl = URL.createObjectURL(blob);
        needRevoke = true;
      };


      const link = document.createElement('a');
      link.href = `${baseUrl}${val.url}`;


      const lastIndex = val.url.lastIndexOf('_');//找到最后一个“_”的位置
      let fileName: string;

      if (lastIndex !== -1) {
        fileName = val.url.substring(lastIndex + 1);//截取“_”后面的所有字符串
      } else {
        const fileType = val.type || 'txt';
        fileName = `未知.${fileType}`
      };

      link.download = decodeURIComponent(fileName);//用于设置下载文件的文件名

      // link.download = `${index+1}.${val.type}`;


      // 添加错误处理
      link.onerror = async (error) => {
        alert("文件未找到，请检查链接的合法性。");
        return;
      };

      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      // URL.revokeObjectURL(val.url);


    } catch (error) {
      alert("下载文件失败，请检查链接的合法性和网络连接。");
      return;
    }
  }
};

// 导出文件功能
export const downloadFromEndpoint = async (method: any, endpoint: any, Data: any) => {
  try {
    const response = await request({
      url: endpoint,
      method: method,
      responseType: "blob", // 重要：设置响应类型为 blob
      data: Data, // 添加请求参数
      headers: {
        "Content-Type": "application/json", // 根据实际情况设置请求头
      },
    });

    // 从响应头中获取文件名
    const contentDisposition = response.headers['content-disposition'];
    let fileName = 'export.xlsx'; // 默认文件名
    if (contentDisposition) {
      const fileNameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
      if (fileNameMatch && fileNameMatch[1]) {
        fileName = fileNameMatch[1].replace(/['"]/g, '').replace('UTF-8', '');
        // 尝试解码 URL 编码的文件名（如包含中文的情况）
        try {
          fileName = decodeURIComponent(fileName);
        } catch (e) {
          console.warn("文件名解码失败，使用原始名称:", fileName);
        }
      }
    }

    const blob = new Blob([response.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
    });

    const url = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.setAttribute("download", fileName);
    link.style.visibility = "hidden";

    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } catch (error) {
    console.error("下载文件出错:", error);
  }
};

//TODO 预览文件
export function openPreviewInNewWindow(fileUrl: string, fileName: string = '') {
  // const fullUrl = 'http://192.168.0.91:19081' + encodeURIComponent(fileUrl);
  // const fullUrl = 'http://222.191.254.54:8888' + encodeURIComponent(fileUrl);

  // const baseUrl = import.meta.env.VITE_SERVE;
  const baseUrl = "http://192.168.0.91:19081";
  const fullUrl = new URL(fileUrl, baseUrl).href;

  const extension = fileUrl.split('.').pop()?.toLowerCase();

  if (extension == 'xlsx' || extension == 'docx' || extension == 'xls') {

    // 创建新窗口
    const newWindow = window.open("", '_blank');
    // const newWindow = window.open("", '_blank');


    if (!newWindow) {
      alert('请允许弹出窗口以查看文件预览')
      return
    };


    // 创建Vue应用
    /* const app = createApp(
      defineComponent({
        render() {
          return h(PreviewDocumentVue, { fileUrl, fileName })
        }
      })
    ) */

    const app = createApp({
      render() {
        return h(PreviewDocumentVue, {
          fileUrl: fileUrl, // 完整URL传给组件
          fileName
        });
      }
    });

    // 挂载到新窗口的document.body
    const container = document.createElement('div')
    newWindow.document.body.appendChild(container)
    app.mount(container)

    // 添加基本样式
    const style = document.createElement('style')
    style.textContent = `
      body { margin: 0; font-family: Arial, sans-serif; }
      html, body { height: 100vh;width:100vw; }
    `
    newWindow.document.head.appendChild(style)

    // 窗口关闭时清理
    newWindow.onbeforeunload = () => {
      app.unmount()
    }

    return newWindow
  } else {
    // 创建新窗口
    const newWindow = window.open(fullUrl, '_blank');


    if (!newWindow) {
      alert('请允许弹出窗口以查看文件预览')
      return
    };


    // 创建Vue应用
    const app = createApp(
      defineComponent({
        render() {
          return h(PreviewDocumentVue, { fileUrl, fileName })
        }
      })
    )

    // 挂载到新窗口的document.body
    const container = document.createElement('div')
    newWindow.document.body.appendChild(container)
    app.mount(container)

    // 添加基本样式
    const style = document.createElement('style')
    style.textContent = `
      body { margin: 0; font-family: Arial, sans-serif; }
      html, body { height: 100%;width:100%; }
    `
    newWindow.document.head.appendChild(style)

    // 窗口关闭时清理
    newWindow.onbeforeunload = () => {
      app.unmount()
    }

    return newWindow
  }
};
